<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="遇见与成长 - 图腾客户管理系统 - {{title}}">
    <title>{{title}}</title>
    <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
    <link rel="stylesheet" href="/apps/css/fontawesome-free-6.4.0-web/css/all.css">
    <link rel="stylesheet" href="/apps/css/mui.css">
</head>

<body>

    <header class="d-flex align-items-center bg-custom-color p-3">
        <button id="backButton" class="btn btn-primary rounded-circle me-3" style="background-color: white;" onclick="history.back();">
            <i class="fas fa-arrow-left custom-color"></i>
        </button>
        <span class="title-text text-white fs-5">{{excerpt}}</span>
    </header>

    <div id="systemNotification" class="alert alert-info alert-dismissible fade show" role="alert" style="display: none;">
        <!-- 通知内容 -->
        <strong>{{notification}}</strong>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-lable="Close"></button>
    </div>

    <div class="container">

        <div class="content">

            <div class="row">
                <div class="col-12">
                    <p>{{{description}}}</p>
                </div>
            </div>

            <!-- INSERT BODY BEGIN -->
            <div class="row" id="inputForm" tabindex="-1" aria-lableledby="inputFormLabel" aria-hidden="true">
                <!-- 输入最新跟进记录的表单 -->
                <form id="inputForm">
                    <div class="row">
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="creator_uid" class="form-lable">创建人UID</lable>
                                <select id="creator_uid" name="creator_uid" class="form-control">
                                    <option value="0">当前用户-无需输入</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="stage" class="form-lable">线索阶段</lable>
                                <select id="stage" name="stage" class="form-control">
                                    {{#each stages}}
                                    <option {{this.selected}} value="{{this.value}}">{{this.name}}</option>
                                    {{/each}}
                                </select>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="source" class="form-lable">线索来源</lable>
                                <input id="source" type="text" class="form-control" name="source" value="" placeholder="例：YY年MM月DD日某会议" required>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="pathway" class="form-lable">获取方式</lable>
                                <input id="pathway" type="text" class="form-control" name="pathway" value="" placeholder="例：微信推荐、见面获得、根据名单" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="contact" class="form-lable">联系姓名</lable>
                                <input id="contact" name="contact" type="text" class="form-control" value="" placeholder="" required>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="phone" class="form-lable">手机号码</lable>
                                <input id="phone" name="phone" type="tel" class="form-control" pattern="[0-9]{3}-[0-9]{2}-[0-9]{4}" value="" placeholder="">
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="email" class="form-lable">电子邮件</lable>
                                <input id="email" name="email" type="email" class="form-control" value="" placeholder="">
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="wechat" class="form-lable">其它方式</lable>
                                <input id="wechat" name="wechat" type="text" class="form-control" value="" placeholder="例如：微信号wx，企业微信介绍，现场">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-6">
                            <div class="mb-2">
                                <lable for="organization" class="form-lable">单位名称</lable>
                                <input id="organization" name="organization" type="text" class="form-control" value="" placeholder="">
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="department" class="form-lable">科室部门</lable>
                                <input id="department" name="deparment" type="text" class="form-control" value="" placeholder="">
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="title" class="form-lable">职务职称</lable>
                                <input id="title" name="title" type="text" class="form-control" value="" placeholder="">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-9">
                            <div class="mb-2">
                                <lable for="remark" class="form-lable">情况说明</lable>
                                <textarea id="remark" name="remark" class="form-control" rows="3" value="" placeholder="请在此详细说明线索情况，如果有相关背景材料可以通过附件上传"></textarea>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="attachment" class="form-lable">相关附件</lable>
                                <input id="attachment" id="attachment" type="file" class="form-control" multiple onchange="uploadFiles(this.files)">
                            </div>
                            <div class="mb-2">
                                <lable for="uploadedFiles" class="form-lable">已传附件</lable>
                                <ul id="uploadedFilesList" name="uploadedFilesList" class="list-unstyled"></ul>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="priority" class="form-lable">优先级别</lable>
                                <select id="priority" name="priority" class="form-control">
                                    <option value="0">0-默认</option>
                                    <option value="1">1-优先</option>
                                    <option value="2">2-紧急</option>
                                    <option value="3">3-特急</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="follower_uid" class="form-lable">跟进人UID</lable>
                                <select id="follower_uid" name="follower_uid" class="form-control">
                                    {{#each followers}}
                                    <option {{this.selected}} value="{{this.value}}">{{this.name}}</option>
                                    {{/each}}
                                </select>
                            </div>
                        </div>
                        <!--div class="col-3">
                            <div class="mb-2">
                                <lable for="forecast_unit" class="form-lable">预测单位</lable>
                                <select id="forecast_unit" name="forecast_unit" class="form-control" value="" placeholder="">
                                    <option value="npm">npm-每月新荐</option>
                                </select>
                            </div>
                        </div-->
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="sales_forecast" class="form-lable">销售预测（npm-每月新荐）</lable>
                                <input id="sales_forecast" name="sales_forecast" type="number" step="1" min="0" class="form-control" value="0" placeholder="">
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="mb-2">
                                <lable for="related_clients" class="form-lable">关联客户</lable>
                                <input id="related_clients" name="related_clients" type="text" class="form-control" class="form-control" value="" placeholder="输入已关联客户UID号，多个号以逗号隔开">
                            </div>
                        </div>
                    </div>

                    <button type="button" class="btn btn-primary" onclick="createRecord();">添加记录</button>
                </form>

            </div>
            <!-- INSERT BODY END-->

            <nav aria-label="Page navigation" class="pagination-container">
                <button id="homeButton" class="btn btn-primary position-absolute top-0 start-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="window.location.href='https://totemlife.cn/apps/crm/';">
                    <i class="fas fa-home" style="color:white;"></i>
                </button>
                <button id="formButton" class="btn btn-primary position-absolute top-0 end-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="searchInPage();">
                    <i class="fas fa-search" style="color: white;"></i>
                </button>
                <ul class="pagination">
                    {{{paginator}}}
                </ul>
            </nav>

        </div>

    </div>

    <!-- Footer with Back Button and Search Button -->
    <footer class="footer" style="text-align: center;">
        <div class="row">
            <div class="text-muted">&nbsp;</div>
            <div class="text-muted">&nbsp;</div>
            <div class="text-muted">&copy;2023 图腾生命医学</div>
            <div class="text-muted">我们为人类免疫事业而奉献</div>
        </div>
    </footer>

    <!-- JavaScript scripts -->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="/apps/js/bootstrap.bundle.min.js"></script>
    <script src="/apps/js/crm-hbs-utils.js"></script>
    <script src="/apps/js/wx-client-dom.js"></script>

    <script>
    const totemUID = parseInt("{{totemUID}}") || 0;
    let attachmentUrls = []; //这个是真正POST时候提交给attachments字段的数据
    let selectedFileNames = [];

    function clearFormInput() {
        // 清空表单内容
        const formInputs = document.querySelectorAll('#inputForm input, #inputForm textarea');
        formInputs.forEach(input => { input.value = ''; });
        attachmentUrls = [];
        selectedFileNames = [];
        // 获取已上传文件列表容器，清空已上传文件列表
        const uploadedFilesList = document.getElementById('uploadedFilesList');
        uploadedFilesList.innerHTML = '';
    };

    async function createRecord() {

        //const foo = document.getElementById('foo').value;
        //if (!foo || foo == '' || foo.length < 3 ) { showSystemNotification("请输入有意义的跟进记录", 'error'); return false; };
        const stage = parseFloat(document.getElementById('stage').value).toFixed(2);
        const source = document.getElementById('source').value;
        if (!source || source == '' || source.length < 3 ) { showSystemNotification("请输入有意义的线索来源", 'error'); return false; };
        const pathway = document.getElementById('pathway').value;
        if (!pathway || pathway == '' || pathway.length < 3 ) { showSystemNotification("请输入有意义的获取方式", 'error'); return false; };
        const follower_uid = parseInt(document.getElementById('follower_uid').value);
        const contact = document.getElementById('contact').value;
        if (!contact || contact == '' || contact.length < 2 ) { showSystemNotification("请输入有意义的联系姓名", 'error'); return false; };
        const phone = document.getElementById('phone').value;
        const email = document.getElementById('email').value;
        const wechat = document.getElementById('wechat').value;
        const pew = phone + email + wechat;
        if (!pew || pew == '' || pew.length < 3 ) { showSystemNotification("请输入至少一种联系方式（电话、电邮、其他）", 'error'); return false; };
        const organization = document.getElementById('organization').value;
        const department = document.getElementById('department').value;
        const title = document.getElementById('title').value;
        const remark = document.getElementById('remark').value;
        if (!remark || remark == '' || remark.length < 5 ) { showSystemNotification("请输入有意义的线索说明", 'error'); return false; };
        const priority = parseInt(document.getElementById('priority').value);
        const sales_forecast = parseInt(document.getElementById('sales_forecast').value);
        const forecast_unit = document.getElementById('forecast_unit').value;
        const related_clients = document.getElementById('related_clients').value;

        try {
            const response = await fetch('/apps/api/create-sales-lead', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    stage, source, follower_uid, contact, phone, email, wechat, organization, department, title, remark, priority, sales_forecast, forecast_unit, related_clients, attachments: attachmentUrls
                })
            });
            if (!response.ok) {
                showSystemNotification(`添加记录失败，请稍后再试：HTTP ERROR - ${response.status}`, 'error'); // 错误通知
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            // Parse the JSON response
            const jsonData = await response.json();
            // Access the fields in the JSON object
            const errcode = jsonData.errcode;
            const errmsg = jsonData.errmsg;
            const id = jsonData.id;
            if (errcode==0) {
                showSystemNotification("小伙伴，大功告成！新记录已成功添加", 'success');
                clearFormInput();
            }else{
                showSystemNotification(`${errcode} ${errmsg}`, 'error'); // 错误通知
            }
        } catch (error) {
            console.error('Error:', error);
            showSystemNotification("添加记录失败，请稍后再试-ERR2", 'error'); // 错误通知
        }
    }

    async function uploadFiles(files, code='assifiedddUserProfile') {
        const formData = new FormData();
        formData.append('uid', totemUID);
        formData.append('code', code);
        let fileName = 'UNTITLED';
        Array.from(files).forEach((file) => {
            formData.append('file', file);
            fileName = file.name;
        });
        const uploadUrl = 'https://mall.totembio.cn/api/uploadMtaFile'; // 后端文件传接口地址
        const response = await fetch(uploadUrl, {
            method: 'POST',
            body: formData,
        });
        if (response.ok) {
            const responseData = await response.json();
            const uploadedSrc = responseData?.data?.src;
            attachmentUrls.push(uploadedSrc); // 将上传成功的附件链接保存到 attachmentUrls 数组中
            selectedFileNames.push(fileName); // 记录所选文件的名称
            showUploadedFilesList();
        } else {
            alert('文件上传失败！');
        }
    }

    function showUploadedFilesList() {
        // 获取已上传文件列表容器
        const uploadedFilesList = document.getElementById('uploadedFilesList');
        // 清空已上传文件列表
        uploadedFilesList.innerHTML = '';
        // 填充已上传文件链接到列表中
        attachmentUrls.forEach((url, index) => {
            const listItem = document.createElement('li');
            const fileName = selectedFileNames[index]; // 获取对应文件的本地名称
            listItem.innerHTML = `
                <span><a href="#" onclick="openFile('${url}', '${fileName}')">${fileName}</a></span>
                <span style="color: red; cursor: pointer;" onclick="removeAttachment(${index})">删除附件</span>
                `;
            uploadedFilesList.appendChild(listItem);
        });
    }

    function openFile(url, fileName) {
        const fileURL = `${url}`; // 构建完整的文件 URL
        const newWindow = window.open(fileURL, '_blank');
        if (newWindow) {
            newWindow.document.write(`<html><head><title>${fileName}</title></head><body><h1>${fileName}</h1><iframe src="${fileURL}" style="width:100%; height:100vh;"></iframe></body></html>`);
        } else {
            alert('请允许弹出窗口以查看文件');
        }
    }

    // 新增移除已上传文件链接的函数
    function removeAttachment(index) {
        // 从 attachmentUrls 数组中移除指定索引的链接
        attachmentUrls.splice(index, 1);
        selectedFileNames.splice(index, 1);
        showUploadedFilesList();
    }

    function searchInPage() {
        let searchText = window.prompt("请输入内容，匹配部分将被高亮显示", "");
        if (searchText && window.find && window.getSelection) {
            document.designMode = "on";
            var sel = window.getSelection();
            sel.collapse(document.body, 0);
            while (window.find(searchText)) {
                document.execCommand("HiliteColor", false, "#88b04b"); // 高亮显示匹配项
                sel.collapseToEnd();
            }
            document.designMode = "off";
        }
    }

    function showSystemNotification(message, type='info' ) {
        if ( !message || message == '') return;
        const systemNotification = document.getElementById('systemNotification');
        const notificationContent = systemNotification.querySelector('.alert strong');

        notificationContent.textContent = message; // 更新通知内容
        // 根据类型设定通知样式
        if (type === 'success') {
            systemNotification.classList.remove('alert-danger'); // 移除错误样式
            systemNotification.classList.add('alert-success'); // 添加成功样式
        } else if (type === 'error') {
            systemNotification.classList.remove('alert-success'); // 移除成功样式
            systemNotification.classList.add('alert-danger'); // 添加错误样式
        }

        systemNotification.style.display = 'block'; // 显示通知

        setTimeout(() => {
            systemNotification.style.display = 'none'; // 5秒后隐藏通知
        }, 8000);
    }

    showSystemNotification("{{notification}}");

    </script>

</body>
</html>
